﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace RESP_IIWaterAssessment
{
    public partial class ProductionForm : Form
    {
        public ProductionForm()
        {
            InitializeComponent();
        }

        int cultID, productKindID;
        tb_product product;
        tb_productkind productkind;
        bool insert = false;

        private void ProductionForm_Load(object sender, EventArgs e)
        {
            cbCulture.SelectedIndexChanged -= cbCulture_SelectedIndexChanged;
            cbCultureProduction.SelectedIndexChanged -= cbCultureProduction_SelectedIndexChanged;

            cbCulture.DataSource = UtilClass.GetCBCultureDataSourse();
            cbCultureProduction.DataSource = UtilClass.GetCBCultureDataSourse();

            cbCulture.DisplayMember = cbCultureProduction.DisplayMember = "Name";
            cbCulture.ValueMember = cbCultureProduction.ValueMember = "ID";
            cbCulture.SelectedIndex = cbCultureProduction.SelectedIndex = -1;

            cbCulture.SelectedIndexChanged += new EventHandler(cbCulture_SelectedIndexChanged);
            cbCultureProduction.SelectedIndexChanged += new EventHandler(cbCultureProduction_SelectedIndexChanged);
        }

        private void cbCultureProduction_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbCultureProduction.SelectedIndex >= 0)
            {
                cbProductKind.SelectedIndexChanged -= cbProductKind_SelectedIndexChanged;

                cultID = Convert.ToInt32(cbCultureProduction.SelectedValue);
                cbProductKind.Enabled = true;

                if (InformationClass.Lang)
                    cbProductKind.DataSource = DBClass.ProductKids
                        .Where(wh => wh.CultureID == cultID)
                        .Select(se => new
                        {
                            Name = se.Name,
                            ID = se.ID
                        })
                        .OrderBy(o => o.Name)
                        .ToArray();
                else
                    cbProductKind.DataSource = DBClass.ProductKids
                        .Where(wh => wh.CultureID == cultID)
                        .Select(se => new
                        {
                            Name = se.NameUz,
                            ID = se.ID
                        })
                        .OrderBy(o => o.Name)
                        .ToArray();
                cbProductKind.DisplayMember = "Name";
                cbProductKind.ValueMember = "ID";
                cbProductKind.SelectedIndex = -1;
                cbProductKind.Text = string.Empty;

                cbProductKind.SelectedIndexChanged += new EventHandler(cbProductKind_SelectedIndexChanged);

                dgvProduction.DataSource = null;
            }
        }

        private void cbProductKind_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbProductKind.SelectedIndex >= 0)
            {
                ShowProduction();
            }
        }

        private void ShowProduction()
        {
            productKindID = Convert.ToInt32(cbProductKind.SelectedValue);

            dgvProduction.DataSource = DBClass.Products
                .Where(wh => wh.ProductKindID == productKindID)
                .Select(se => new
                {
                    ID = se.ID,
                    NameRu = se.Name,
                    NameUz = se.NameUz
                }).ToList();

            dgvProduction.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvProduction.Columns["ID"].Visible = false;
            dgvProduction.Columns["NameRu"].HeaderText = "Русское название";
            dgvProduction.Columns["NameUz"].HeaderText = "Узбекское название";
            dgvProduction.AutoResizeColumns();
        }

        private void cbCulture_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbCulture.SelectedIndex >= 0)
            {
                ShowProductionKind();
            }
        }

        private void ShowProductionKind()
        {
            cultID = Convert.ToInt32(cbCulture.SelectedValue);
            dgvProductKind.DataSource = DBClass.ProductKids
                .Where(wh => wh.CultureID == cultID)
                .Select(se => new
                {
                    ID = se.ID,
                    NameRu = se.Name,
                    NameUz = se.NameUz
                }).ToList();

            dgvProductKind.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvProductKind.Columns["ID"].Visible = false;
            dgvProductKind.Columns["NameRu"].HeaderText = "Русское название";
            dgvProductKind.Columns["NameUz"].HeaderText = "Узбекское название";
            dgvProductKind.AutoResizeColumns();

        }

        private void tsbAddProductKind_Click(object sender, EventArgs e)
        {
            groupBox1.Visible = insert = true;
            tbNameRus.Text = tbNameUz.Text = string.Empty;
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            groupBox1.Visible = insert = false;
            productkind = null;
        }

        private void buttonAccept_Click(object sender, EventArgs e)
        {
            if (cbCulture.SelectedIndex < 0 || String.IsNullOrEmpty(tbNameRus.Text) || String.IsNullOrEmpty(tbNameUz.Text))
            {
                if (InformationClass.Lang)
                    MessageBox.Show("Заполнены не все ключевые параметры.");
                else
                    MessageBox.Show("Асосий параметрларнинг барчаси тўлдирилмаган.");
                return;
            }

            if (insert)
            {
                productkind = new tb_productkind
                {
                    CultureID = Convert.ToInt32(cbCulture.SelectedValue),
                    Name = tbNameRus.Text,
                    NameUz = tbNameUz.Text
                };

                DBClass.ProductKids.InsertOnSubmit(productkind);
            }
            else
            {
                if (productkind != null)
                {
                    productkind.CultureID = Convert.ToInt32(cbCulture.SelectedValue);
                    productkind.Name = tbNameRus.Text;
                    productkind.NameUz = tbNameUz.Text;
                }
            }
            try
            {
                if (DBClass.RESPContext.GetChangeSet().Deletes.Count > 0 || DBClass.RESPContext.GetChangeSet().Inserts.Count > 0 || DBClass.RESPContext.GetChangeSet().Updates.Count > 0)
                {
                    DBClass.RESPContext.SubmitChanges();
                    MessageBox.Show(msgClass.msgSubmitChanges, msgClass.msgAchtung);
                }
                productkind = null;
                groupBox1.Visible = insert = false;
                ShowProductionKind();
            }
            catch
            {
                MessageBox.Show(msgClass.msgError, msgClass.msgAchtung); ;
            }

        }

        private void tsbEditProductKind_Click(object sender, EventArgs e)
        {
            if (dgvProductKind.RowCount > 0)
            {
                insert = false;
                groupBox1.Visible = true;
                int pkID = (int)dgvProductKind["ID", dgvProductKind.CurrentRow.Index].Value;
                productkind = DBClass.ProductKids.Where(wh => wh.ID == pkID).SingleOrDefault();
                cbCulture.SelectedValue = productkind.CultureID;
                tbNameRus.Text = productkind.Name;
                tbNameUz.Text = productkind.NameUz;
            }
        }

        private void tsbDeleteProductKind_Click(object sender, EventArgs e)
        {
            if (dgvProductKind.RowCount > 0)
            {
                string msg = InformationClass.Lang ? "Вы действительно хотите удалить Вид продукции?" : "Сиз ҳақиқатдан ҳам Маҳсулот турини олиб ташламоқчимисиз?";

                if (MessageBox.Show(msg, msgClass.msgAchtung, MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    int pkID = (int)dgvProductKind["ID", dgvProductKind.CurrentRow.Index].Value;
                    productkind = DBClass.ProductKids.Where(wh => wh.ID == pkID).SingleOrDefault();
                    DBClass.ProductKids.DeleteOnSubmit(productkind);
                    DBClass.RESPContext.SubmitChanges();
                    ShowProductionKind();
                }
            }
        }

        private void tsbAddProduction_Click(object sender, EventArgs e)
        {
            groupBox2.Visible = insert = true;
            tbProductionNameRus.Text = tbProductionNameUz.Text = string.Empty;
        }

        private void tsbEditProduction_Click(object sender, EventArgs e)
        {
            if (dgvProduction.RowCount > 0)
            {
                insert = false;
                groupBox2.Visible = true;
                int prID = (int)dgvProduction["ID", dgvProduction.CurrentRow.Index].Value;
                product = DBClass.Products.Where(wh => wh.ID == prID).SingleOrDefault();
                tbProductionNameRus.Text = product.Name;
                tbProductionNameUz.Text = product.NameUz;
                cbProductKind.SelectedValue = product.ProductKindID;
            }
        }

        private void tsbDeleteProduction_Click(object sender, EventArgs e)
        {
            if (dgvProduction.RowCount > 0)
            {
                string msg = InformationClass.Lang ? "Вы действительно хотите удалить Продукцию?" : "Сиз ҳақиқатдан ҳам Маҳсулотни олиб ташламоқчимисиз?";

                if (MessageBox.Show(msg, msgClass.msgAchtung, MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    insert = false;
                    groupBox2.Visible = true;
                    int prID = (int)dgvProduction["ID", dgvProduction.CurrentRow.Index].Value;
                    product = DBClass.Products.Where(wh => wh.ID == prID).SingleOrDefault();
                    DBClass.Products.DeleteOnSubmit(product);
                    DBClass.RESPContext.SubmitChanges();
                    ShowProduction();
                }
            }
        }

        private void buttonCancelProduction_Click(object sender, EventArgs e)
        {
            product = null;
            groupBox2.Visible = false;

        }

        private void buttonAcceptProduction_Click(object sender, EventArgs e)
        {
            if (cbProductKind.SelectedIndex < 0)
            {
                if (InformationClass.Lang)
                    MessageBox.Show("Не выбран Вид продукции.");
                else
                    MessageBox.Show("Маҳсулот тури танланмади.");
                return;
            }
            else if (string.IsNullOrEmpty(tbProductionNameRus.Text) || string.IsNullOrEmpty(tbProductionNameUz.Text))
            {
                if (InformationClass.Lang)
                    MessageBox.Show("Не заполненны названия");
                else
                    MessageBox.Show("Номлари тўлдирилмади");
                return;
            }

            if (insert)
            {
                product = new tb_product
                {
                    Name = tbProductionNameRus.Text,
                    NameUz = tbProductionNameUz.Text,
                    ProductKindID = Convert.ToInt32(cbProductKind.SelectedValue)
                };
                DBClass.Products.InsertOnSubmit(product);
            }
            else if (product != null)
            {
                product.ProductKindID = Convert.ToInt32(cbProductKind.SelectedValue);
                product.Name = tbProductionNameRus.Text;
                product.NameUz = tbProductionNameUz.Text;
            }
            try
            {
                DBClass.RESPContext.SubmitChanges();
                MessageBox.Show(msgClass.msgSubmitChanges, msgClass.msgAchtung);
                product = null;
                groupBox2.Visible = insert = false;
                ShowProduction();
            }
            catch
            {
                MessageBox.Show(msgClass.msgError, msgClass.msgAchtung);
            }

        }
    }
}
